<script setup lang="tsx">
import {
  pageCommissionOrderApi,
  adminPageCommissionOrderApi,
  exportCommissionExcelApi,
  adminExportCommissionExcelApi
} from '@/api/Order'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { useUserStore } from '@/store/modules/user'
import { businessListApi } from '@/api/merchantManagement'
import { formatTime } from '@/utils'
const userStore = useUserStore()

const { t } = useI18n()

const activeTab = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const api = userStore.userInfo.roles.includes('商家')
      ? adminPageCommissionOrderApi
      : pageCommissionOrderApi
    const res = await api({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const searchRef = ref()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'orderNo',
    label: '订单编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'activeKeyword',
    label: '活动名称',
    search: {
      componentProps: {
        placeholder: '请输入活动ID/活动名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>{row.activeTitle}</div>
              <div class={'flex items-center'}>ID:{row.activeId}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'businessShortName',
    label: '商家简称',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: userStore.userInfo.roles.includes('商家')
    }
  },
  {
    field: 'agentKeyword',
    label: '经纪人',
    search: {
      componentProps: {
        placeholder: '请输入经纪人姓名/手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>{row.agentNickName}</div>
              <div class={'flex items-center'}>{row.agentMobile}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'businessId',
    label: '商家',
    search: {
      hidden: userStore.userInfo.roles.includes('商家'),
      component: 'Select',
      optionApi: async () => getBusinessList()
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'orderPrice',
    label: '订单总价',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'payPrice',
    label: '实付金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'actualCommissionAmt',
    label: '预估佣金',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'settledCommissionAmt',
    label: '结算佣金',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'orderTime',
    label: '下单时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { orderTime, ...rest } = params
  let orderTimeStart, orderTimeEnd
  if (orderTime && orderTime.length > 0) {
    orderTimeStart = orderTime[0]
    orderTimeEnd = orderTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    orderTimeStart,
    orderTimeEnd,
    ...rest
  }
  getList()
}
const getBusinessList = async () => {
  const res = await businessListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.businessShortName,
    value: v.id
  }))
}
const handleDownload = async (params: any) => {
  const { orderTime, ...rest } = params
  let orderTimeStart, orderTimeEnd
  if (orderTime && orderTime.length > 0) {
    orderTimeStart = orderTime[0]
    orderTimeEnd = orderTime[1]
  }
  const currentDate = new Date()
  const time = formatTime(currentDate, 'yyyyMMddHHmmss')
  const num = Math.floor(Math.random() * 900000) + 100000
  const downloadApi = userStore.userInfo.roles.includes('商家')
    ? adminExportCommissionExcelApi
    : exportCommissionExcelApi
  const res = await downloadApi({
    orderTimeStart,
    orderTimeEnd,
    ...rest
  })
  const correctMimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  let link = document.createElement('a')
  link.href = url
  link.download = `佣金查询${time}${num}`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        ref="searchRef"
        :schema="allSchemas.searchSchema"
        :show-download="true"
        @download="handleDownload"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
  </div>
</template>
